﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using BlogEngine.Core;

public partial class admin_ManagePosts : System.Web.UI.Page
{
	private const int Count = 20;
	private int _page;

	/// <summary>
	/// Handles the PreInit event of the Page control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void Page_PreInit(object sender, EventArgs e)
	{
		string qpage = Request.QueryString["page"];

		if (!Int32.TryParse(qpage, out _page))
			_page = 1;
	}

	/// <summary>
	/// Handles the Load event of the Page control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void Page_Load(object sender, EventArgs e)
	{
		DataBind();
	}

	/// <summary>
	/// Binds a data source to the invoked server control and all its child controls.
	/// </summary>
	public override void DataBind()
	{
		backwardLink.Visible = false;
		forwardLink.Visible = false;

		var posts = Post.GetPosts((_page - 1) * Count, Count);
		postsGrid.DataSource = posts;
		postsGrid.DataBind();

		if (_page > 1)
		{
			backwardLink.Visible = true;
			backwardLink.NavigateUrl = "manage-posts.aspx?page=" + (_page - 1);
		}

		if (posts.Count == Count)
		{
			forwardLink.Visible = true;
			forwardLink.NavigateUrl = "manage-posts.aspx?page=" + (_page + 1);
		}
	}

	protected void postsGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
	{
		if (e.Keys.Count > 0 && e.Keys[0] is int)
		{
			Post post = Post.GetPost((int)e.Keys[0]);
			post.Delete();
		}
		DataBind();
	}
}
